﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using Splashscreen;
using System.Threading;
using SARD.Aux_Forms;
using SARD.Classes;
using System.IO;


///This section of the code will deal with the user interface associated to a dicom image file.
namespace SARD.MainForms
{
    public partial class DicomImageBox : Form
    {

        public enum zoom
        {
           z1 = 1,z2 ,z3 = 5,z4 = 10,z5 = 20,z6 = 50,z7 = 100,
        }

        private string sfile;
        int[,] kernel;
        double z;
        bool selected;
        bool update;
        bool zeroiswhite; // this variable will be used for setting with the zero value must be used for white or black pixels.

        dicomimage dcmimage;
        Point p1, p2;
        Rectangle StartPoint;
        selectionarea selection;


        //Special variable for solving homogeneidade problem:

        int roiarea;
        string[] text;
        bool valid;
        int nx, ny;
        double[] STDroi;
        double[] MPVroi;
        double[] SNRroi;

        double totalMPV;
        double totalSTD;
        double totalsnr;
        bool validtest;


        string file;
        /// <summary>
        /// This is a very basic constructor only used for initializing the interface componets.
        /// </summary>
        public DicomImageBox()
        {
            InitializeComponent();
        }


        /// <summary>
        /// This is the primary constructor in use, it will take a string file name as a parameter and will create the proper image based on that.
        /// </summary>
        /// <param name="FileName">
        /// Dicom file name and path.
        /// </param>
        public DicomImageBox(string FileName) 
        {
            InitializeComponent();
            sfile = FileName;
            Cursor = Cursors.WaitCursor;
            dcmimage = new dicomimage(FileName);
            zeroiswhite = false;
            this.éPretoToolStripMenuItem.Checked = true;
            pictureBox1.Image = dcmimage.display();
            this.adjusttoscreen();
            SetLayout();
            ajustarAoTamanhoDaTelaToolStripMenuItem.Checked = true;
            ajustarAoTamanhoDaTelaToolStripMenuItem1.Checked = true;
            selection = new selectionarea();
            selection.setmode = selectionarea.mode.statical;
            update = false;
                

            // i have to set the operation mode and other parameters here.
            Cursor = Cursors.Default;
            

            //special parameters for homogeneidade

            //text = null;
            //valid = false;
            //roiarea = 0;
            //validtest = false;
        }

        /// <summary>
        /// This function is responsible for showing the dicom tags of the associated file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tagsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<string> str = dcmimage.tags();
            DicomTagsForm tags = new DicomTagsForm();
            tags.SetString(ref str);
            tags.Show();
        }


        /// <summary>
        /// Shows the image parameters such as width and height
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resoluçãoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Largura: " + this.pictureBox1.Image.Width + " Altura: " + this.pictureBox1.Image.Height);
        }


        /// <summary>
        /// Shows the dicom parameters like depth.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void profundidadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Profundidade: " + dcmimage.bitdepth().ToString() + " bits por pixel");
        }


        /// <summary>
        /// In this point the zoom will be added to the image, the default value however is 1.
        /// This value will be changed only by the user over the graphical interface.
        /// </summary>
        private void SetLayout()
        {
            if ((this.pictureBox1.Image != null) && (this.z > 0) )
            {

                if ((int)(this.pictureBox1.Image.Width * this.z / 10) < 10000 && (int)(this.pictureBox1.Image.Height * this.z / 10) < 10000)
                {
                    this.pictureBox1.Width = (int)(this.pictureBox1.Image.Width * this.z / 10);
                    this.pictureBox1.Height = (int)(this.pictureBox1.Image.Height * this.z / 10);
                }
                else 
                {
                    this.z = 1;
                    this.pictureBox1.Width = (int)(this.pictureBox1.Image.Width * this.z / 10);
                    this.pictureBox1.Height = (int)(this.pictureBox1.Image.Height * this.z / 10);
                    MessageBox.Show("Esta imagem está acima do tamanho máximo permitido");
                }

                this.panel1.AutoScroll = true;
                this.CenterImage();
            }


        }


        /// <summary>
        /// The image is centered in the screen.
        /// This is a option not a standard.
        /// </summary>
        private void CenterImage()
        {
            this.panel1.VerticalScroll.Value = 0;
            this.panel1.HorizontalScroll.Value = 0;
            int top = (int)((this.panel1.Height - this.pictureBox1.Height) / 2.0);
            int left = (int)((this.panel1.Width - this.pictureBox1.Width) / 2.0);
            if (top < 0)
                top = 0;
            if (left < 0)
                left = 0;
            this.pictureBox1.Top = top;
            this.pictureBox1.Left = left;
            this.pictureBox1.Refresh();
        }

        private void adjusttoscreen() 
        {
            this.panel1.VerticalScroll.Value = 0;
            this.panel1.HorizontalScroll.Value = 0;
            double zoom;

            zoom = ((double)this.panel1.Height / this.pictureBox1.Image.Height) > ((double)this.panel1.Width / this.pictureBox1.Image.Width) ? ((double)this.panel1.Width / this.pictureBox1.Image.Width) : ((double)this.panel1.Height / this.pictureBox1.Image.Height);

            this.z = 10 * zoom;
            this.Refresh();
        }

        /// <summary>
        /// This function shows informations about the authors.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contatoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.Aux_Forms.Form1 contact = new Form1();
            contact.Show();

        }

        /// <summary>
        /// This function shows informations about the program.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sobreOProgramaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 about = new AboutBox1();
            about.Show();
        }

        /// <summary>
        /// This function is a image filter that inverts the pixels values. 
        /// To do this this one gets the maximum value and subtracts it from the pixel value.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void inverterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (pictureBox1 != null)
            {
                dcmimage.invertimage();
                pictureBox1.Image = dcmimage.display();
            }

        }

        /// <summary>
        /// This function allow the user to select the bright range displayed.
        /// It also has a preview of the image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void janelaDeBrilhoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.Aux_Forms.brightrange bright;

            if (dcmimage.bitdepth() == 16)
            {

                bright = new SARD.Aux_Forms.brightrange(dcmimage.getmin(), dcmimage.getmax(), dcmimage.getoldm(), dcmimage.getoldM(), dcmimage.preview16(128), 128);
                bright.ShowDialog();
                pictureBox1.Image = dcmimage.display(bright.getmin(), bright.getmax());
            }

            if (dcmimage.bitdepth() == 8)
            {
                bright = new SARD.Aux_Forms.brightrange(dcmimage.getmin(), dcmimage.getmax(), dcmimage.getoldm(), dcmimage.getoldM(), dcmimage.preview8(128), 128);
                bright.ShowDialog();
                pictureBox1.Image = dcmimage.display(bright.getmin(), bright.getmax());
            }
        
        }

        /// <summary>
        /// This function is a image filter.
        /// It calculates the average value over the neighorhood pixels.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ifToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int[,] k = new int[,] {     { 1, 1, 1 },
										{ 1, 1, 1 },
										{ 1, 1, 1 } };
            dcmimage.convolution(k);
            this.pictureBox1.Image = dcmimage.display();
        }

        /// <summary>
        /// This is a image filter.
        /// This filter is a Sobel filter (responsible for finding the image edges).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void filtor1ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// This function is a image filter.
        /// This filter is a gaussian blurr. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void filToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int[,] k = new int[,] {     { 1, 2, 1 },
										{ 2, 4, 2 },
										{ 1, 2, 1 } };
            dcmimage.convolution(k);
            this.pictureBox1.Image = dcmimage.display();
        }

        private void inserirKernelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.Aux_Forms.convolutionkernel kernel = new SARD.Aux_Forms.convolutionkernel();
            kernel.ShowDialog();
            this.kernel  = kernel.returnmatrix();

        }

        private void utilizarÚltimoKernelToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (kernel != null)
            {
                if (kernel.Length != 0)
                {
                    dcmimage.convolution(kernel, new Rectangle(0, 0, dcmimage.getwidth(), dcmimage.getheight()));
                    this.pictureBox1.Image = dcmimage.display();
                }
            }
            else
            {
                SARD.Aux_Forms.convolutionkernel kernel2 = new SARD.Aux_Forms.convolutionkernel();
                kernel2.ShowDialog();
                this.kernel = kernel2.returnmatrix();
                if (kernel.Length != 0)
                {
                    Cursor = Cursors.WaitCursor;
                    dcmimage.convolution(kernel, new Rectangle(0, 0, dcmimage.getwidth(), dcmimage.getheight()));
                    this.pictureBox1.Image = dcmimage.display();
                }
 
            }
        }

        private void showoptions(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                p1.X = (int)((float)10 * e.X / z);
                p1.Y = (int)((float)10 * e.Y / z);

                contextMenuStrip1.Show(e.X + this.pictureBox1.Left, e.Y + this.pictureBox1.Top);
            }
        }

        private void selectarea(object sender, PaintEventArgs e)
        {

            if (selected  && (this.selection.setoperation == selectionarea.operation.freesize))
            {
                // Draw a rectangle displaying the current selection
                Pen pen = Pens.Red;
                e.Graphics.DrawRectangle(pen, StartPoint);
                

            }

            if (update) 
            {

                if (StartPoint.Width >= 0 || StartPoint.Height >= 0)
                {
                    // Draw a rectangle displaying the current selection
                    Pen pen = Pens.Red;
                    e.Graphics.DrawRectangle(pen, StartPoint);
                }
                update = false;
            }


            if (selected && (this.selection.setoperation == selectionarea.operation.line)) 
            {
                Pen pen = Pens.Red;
                e.Graphics.DrawLine(pen, p1, p2);
            }

            if (this.selection.setoperation == selectionarea.operation.fixedsize)
            {
                Pen pen = Pens.Red;
                e.Graphics.DrawRectangle(pen, StartPoint);
            }


            if (valid) 
            {
                string write = null;

                foreach (String str in text) 
                {
                    write += str;
                    write += "\n";
                }
                e.Graphics.DrawString(write, new Font("Arial", this.pictureBox1.Image.Width / (int)(32 * z / 10)), Brushes.Red, 0, 0);
                    
                   
            }
            
        }

        private void Start(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && (this.selection.setoperation == selectionarea.operation.freesize))
            {
                selected = true;
                StartPoint = new Rectangle(new Point(e.X, e.Y), new Size());
                pictureBox1.Refresh();
            }

            if (this.selection.setoperation == selectionarea.operation.fixedsize && e.Button == MouseButtons.Left && selected)
            {
                selected = false;
                return;
            }

            if (this.selection.setoperation == selectionarea.operation.fixedsize && e.Button == MouseButtons.Left  && !selected)
            {
                StartPoint.Width = (int)(10 * StartPoint.Width / z);
                StartPoint.Height = (int)(10 * StartPoint.Height / z);
                StartPoint.X = (int)(10 * StartPoint.X / z);
                StartPoint.Y = (int)(10 * StartPoint.Y / z);

                selected = true;
            }

            if (e.Button == MouseButtons.Left && (this.selection.setoperation == selectionarea.operation.line)) 
            {
                selected = true;
                p1 = new Point(e.X, e.Y);
                pictureBox1.Refresh();
 
            }


        }

        private void setareasize(object sender, MouseEventArgs e)
        {


            // Update the actual size of the selection:
            if (selected && (this.selection.setoperation == selectionarea.operation.freesize))
            {
                
                StartPoint.Width = e.X - StartPoint.X;
                StartPoint.Height = e.Y - StartPoint.Y;

                // Redraw the picturebox:
                pictureBox1.Refresh();
            }

            if (selected && (this.selection.setoperation == selectionarea.operation.line))
            {

                p2.X = e.X;
                p2.Y = e.Y;

                // Redraw the picturebox:
                pictureBox1.Refresh();
            }

            if (this.selection.setoperation == selectionarea.operation.fixedsize && !selected)
            {
                StartPoint.Width = (int)(selection.Sizex() * selection.numberx() * z / 10);
                StartPoint.Height = (int)(selection.Sizey() * selection.numbery() * z/10);
                StartPoint.X = e.X;
                StartPoint.Y = e.Y;

                // Redraw the picturebox:
                pictureBox1.Refresh();
            }

            if (this.selection.setoperation == selectionarea.operation.normal)
            {
                this.toolStripTextBox1.Text = Convert.ToString((int)(10 * e.X / z));
                this.toolStripTextBox2.Text = Convert.ToString((int)(10 * e.Y / z));
                this.toolStripTextBox3.Text = Convert.ToString(dcmimage.returnvalue((int)(10 * e.X / z), (int)(10 * e.Y / z)));
            }

           
        }

        private void calculate(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && selected && (this.selection.setoperation == selectionarea.operation.freesize))
            {
                StartPoint.Width = (int)(10 * StartPoint.Width / z);
                StartPoint.Height = (int)(10 * StartPoint.Height / z);
                StartPoint.X = (int)(10 * StartPoint.X / z);
                StartPoint.Y = (int)(10 * StartPoint.Y / z);

                selected = false;
            }

            if (e.Button == MouseButtons.Left && selected && (this.selection.setoperation == selectionarea.operation.line))
            {
                p1.X = (int)(10 * p1.X / z);
                p2.X = (int)(10 * p2.X / z);
                p1.Y = (int)(10 * p1.Y / z);
                p2.Y = (int)(10 * p2.Y / z);

                selected = false;
            }

        }

        private void adicionarÁreaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.MainForms.MainForm main = (SARD.MainForms.MainForm)this.MdiParent;
            main.rect.Add(StartPoint);
            SARD.Aux_Forms.ROI roi = new SARD.Aux_Forms.ROI(main.rect, this.pictureBox1.Image);
            roi.ShowDialog();

            int position = roi.returnindex();

            if (position >= 0)
            {
                StartPoint = main.rect[position];
                update = true;
                pictureBox1.Refresh();
            }
            
        }

        private void calcularToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (this.selection.setmode == selectionarea.mode.statical)
            {
                SARD.Statical calculateit;
                calculateit = new SARD.Statical(ref dcmimage, StartPoint);
                calculateit.Show();
            }
            else if (this.selection.setmode == selectionarea.mode.linearity)
            {
                dicomimage ndicom = new dicomimage();
                ndicom = dcmimage.getimagerectangle(StartPoint);
                int[] vector;
                int[] averagedistribution;
                List<int> points = new List<int>();

                int[,] blurr = { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 }, };
                ndicom.convolution(blurr);

                if (StartPoint.Width > StartPoint.Height)
                {
                    averagedistribution = new int[ndicom.getwidth()];
                    averagedistribution = ndicom.acumulateoveravector(true);
                    int[,] p = {{-1, 0, 1},{-2, 0, 2},{-1, 0, 1},};
                    ndicom.convolution(p);
                    vector = new int[ndicom.getwidth()];
                    vector = ndicom.acumulateoveravector(true);
                }
                else
                {
                    averagedistribution = new int[ndicom.getheight()];
                    averagedistribution = ndicom.acumulateoveravector(false);
                    int[,] p = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 }, };
                    ndicom.convolution(p);
                    vector = new int[ndicom.getheight()];
                    vector = ndicom.acumulateoveravector(false);
                }

                int average =0;

                for (int i = 0; i < vector.Length; i++)
                    average += vector[i];              


                for (int i = 0; i < vector.Length; i++)
                {
                    if (vector[i] > average)
                        vector[i] = 1;
                    else
                        vector[i] = 0;
                }

            }

            if (this.selection.setmode == selectionarea.mode.mtf)
            { 
                /// !!! the MTF calculation will beggin here!!!
            }

            
        }

        private void mostrarÁreaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("X: " + StartPoint.X.ToString() + "    Y: " + StartPoint.Y.ToString() + 
                "    Comprimento: " + StartPoint.Width.ToString() + "    Altura: " + StartPoint.Height.ToString());
        }

        private void mostarPontoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("X: " + p1.X.ToString() + "    Y: " + p1.Y.ToString());
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z1;
            this.unchekbox();
            this.toolStripMenuItem2.Checked = true;
            this.toolStripMenuItem9.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z2;
            this.unchekbox();
            this.toolStripMenuItem3.Checked = true;
            this.toolStripMenuItem10.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z3;
            this.unchekbox();
            this.toolStripMenuItem4.Checked = true;
            this.toolStripMenuItem11.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z4;
            this.unchekbox();
            this.toolStripMenuItem5.Checked = true;
            this.toolStripMenuItem12.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z5;
            this.unchekbox();
            this.toolStripMenuItem6.Checked = true;
            this.toolStripMenuItem13.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z6;
            this.unchekbox();
            this.toolStripMenuItem7.Checked = true;
            this.toolStripMenuItem14.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z7;
            this.unchekbox();
            this.toolStripMenuItem8.Checked = true;
            this.toolStripMenuItem15.Checked = true;
            this.SetLayout();
        }

        private void load(object sender, EventArgs e)
        {
            this.pictureBox1.Width = 0;
            this.pictureBox1.Height = 0;
            this.SetLayout();
        }

        private void mTFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.selection.setoperation = selectionarea.operation.fixedsize;
        }

        private void selecionarÁreaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Este módulo ainda não foi implementado");
            /*this.selection.setoperation = selectionarea.operation.fixedsize;
            this.selection.setmode = selectionarea.mode.mtf;*/
        }

        private void determinarParâmetrosToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Este módulo ainda não foi implementado");
            /*SARD.Aux_Forms.MTFform mtf = new SARD.Aux_Forms.MTFform();
            mtf.ShowDialog();

            this.selection.setoperation = selectionarea.operation.fixedsize;
            this.selection.setmode = selectionarea.mode.mtf;
            this.selection.setsize(mtf.returnsize(), mtf.returnsize());*/

        }

        private void unchekbox() 
        {
            toolStripMenuItem2.Checked = false;
            toolStripMenuItem3.Checked = false;
            toolStripMenuItem4.Checked = false;
            toolStripMenuItem5.Checked = false;
            toolStripMenuItem6.Checked = false;
            toolStripMenuItem7.Checked = false;
            toolStripMenuItem8.Checked = false;
            toolStripMenuItem9.Checked = false;
            toolStripMenuItem10.Checked = false;
            toolStripMenuItem11.Checked = false;
            toolStripMenuItem12.Checked = false;
            toolStripMenuItem13.Checked = false;
            toolStripMenuItem14.Checked = false;
            toolStripMenuItem15.Checked = false;
            ajustarAoTamanhoDaTelaToolStripMenuItem.Checked = false;
            ajustarAoTamanhoDaTelaToolStripMenuItem1.Checked = false;
        }

        private void áreaDeTamanhoVariávelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.selection.setmode = selectionarea.mode.statical;
            this.selection.setoperation = selectionarea.operation.freesize;

        }

        private void áreaDeTamanhoFixoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
          
            MTFform areasize = new MTFform();
            areasize.ShowDialog();
            this.selection.setmode = selectionarea.mode.statical;
            this.selection.setoperation = selectionarea.operation.fixedsize;
            this.selection.setsize(areasize.returnsizex(), areasize.returnsizey());

            
        }

        private void normalcursor(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            if (this.selection.setoperation == selectionarea.operation.freesize || this.selection.setoperation == selectionarea.operation.line)
                this.Cursor = Cursors.Cross;
              
            if (this.selection.setoperation == selectionarea.operation.normal)
                this.Cursor = Cursors.Hand;
        }

        private void gerarHistogramaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (StartPoint.Width > 0 || StartPoint.Height > 0)
            {
                histogram histogram = new histogram(dcmimage.generatehistogram(StartPoint), dcmimage.maxandmin(StartPoint));
                histogram.Show();
            }
        }

        private void equalizaçãoDeHistogramaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dcmimage.histogramequalizataion();
            pictureBox1.Image = dcmimage.display();

        }

        private void linearidadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.selection.setmode = selectionarea.mode.linearity;
            this.selection.setoperation = selectionarea.operation.freesize;
        }

        private void selecionarRoiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.MainForms.MainForm main = (SARD.MainForms.MainForm)this.MdiParent;
            SARD.Aux_Forms.ROI roi = new SARD.Aux_Forms.ROI(main.rect, this.pictureBox1.Image);
            roi.ShowDialog();
            int position = roi.returnindex();

            if (position > 0)
                StartPoint = main.rect[position];
        }

        private void gerarHistogramaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (StartPoint.Width > 0)
            {
                histogram histogram = new histogram(dcmimage.generatehistogram(StartPoint), dcmimage.maxandmin(StartPoint));
                histogram.Show();
            }
        }

        private void retaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.selection.setmode = selectionarea.mode.statical;
            this.selection.setoperation = selectionarea.operation.line;

            /*
             Attention: The line function is not complete yet. You still need to develop the desired functions to deal with it.
             */
        }

        private void éPretoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zeroiswhite = false;
            this.éBrancoToolStripMenuItem.Checked = false;
            this.éPretoToolStripMenuItem.Checked = true;
            dcmimage.changereadcolor(zeroiswhite);
            pictureBox1.Image = dcmimage.display();
        }

        private void éBrancoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zeroiswhite = true;
            this.éBrancoToolStripMenuItem.Checked = true;
            this.éPretoToolStripMenuItem.Checked = false;
            dcmimage.changereadcolor(zeroiswhite);
            pictureBox1.Image = dcmimage.display();

        }

        private void converterPara0ÉBrancoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zeroiswhite = true;
            this.éBrancoToolStripMenuItem.Checked = true;
            this.éPretoToolStripMenuItem.Checked = false;
            dcmimage.changecolortype(zeroiswhite);
            dcmimage.changereadcolor(zeroiswhite);
            pictureBox1.Image = dcmimage.display();

        }

        private void converterPara0ÉPretoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zeroiswhite = false;
            this.éBrancoToolStripMenuItem.Checked = false;
            this.éPretoToolStripMenuItem.Checked = true;
            dcmimage.changecolortype(zeroiswhite);
            dcmimage.changereadcolor(zeroiswhite);
            pictureBox1.Image = dcmimage.display();

        }

        private void restaurarImagemOriginalToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Cursor = Cursors.WaitCursor;
            dcmimage = new dicomimage(sfile);
            zeroiswhite = false;
            this.éPretoToolStripMenuItem.Checked = true;
            pictureBox1.Image = dcmimage.display();
            SetLayout();
            selection = new selectionarea();
            selection.setmode = selectionarea.mode.statical;
            Cursor = Cursors.Default;
            this.z = (double)zoom.z4;

        }

        private void normalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.selection.setoperation = selectionarea.operation.normal;
        }

        private void exportarParaJpegToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap bmp = (Bitmap)this.pictureBox1.Image;
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "JPEG|*.jpg";
            save.Title = "Salvar";

            save.ShowDialog();
            if (save.FileName != "")
                bmp.Save(save.FileName, ImageFormat.Jpeg);
        }

        private void selecionarÁreaToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.selection.setmode = selectionarea.mode.homogeneidade;
            this.selection.setoperation = selectionarea.operation.freesize;
        }

        private void definirParâmetrosDeCálculoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.Aux_Forms.MTFform selectsize = new MTFform();
            selectsize.ShowDialog();
            roiarea = selectsize.returnsizex();

        }

        private void definirInformaçõesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SARD.Aux_Forms.local showoptions = new local(sfile);
            showoptions.Show();

            file = showoptions.getfile();
            /*
            if (file >= 0 && equipment >= 0 && test >= 0)
            {
                text = new string[23];

                string currentdirectory = Directory.GetCurrentDirectory();
                string[] filePaths = Directory.GetFiles(currentdirectory.ToString(), "*.txt");
                string[] sfile = System.IO.File.ReadAllLines(filePaths[file]);


                List<int> equipmentpos = new List<int>();
                List<int> tpos = new List<int>();
                int i = 0;

                foreach (String str in sfile)
                {
                    if (str.Contains("#Equipamento:"))
                        equipmentpos.Add(i);

                    i++;
                }

                if (equipmentpos.Count > equipment + 1)
                {

                    for (int j = 0; j < equipmentpos[equipment + 1] - equipmentpos[equipment]; j++)
                    {
                        if (sfile[j + equipmentpos[equipment]].Contains("#Teste:"))
                            tpos.Add(j + equipmentpos[equipment]);
                    }

                }
                else
                {
                    for (int j = 0; j < sfile.Length - equipmentpos[equipment]; j++)
                    {
                        if (sfile[j + equipmentpos[equipment]].Contains("#Teste:"))
                            tpos.Add(j + equipmentpos[equipment]);
                    }

                }

                text[0] = sfile[0];
                text[1] = sfile[1];
                text[2] = sfile[2];
                text[3] = sfile[3];
                text[4] = sfile[4];
                text[5] = null;

                text[6] = sfile[equipmentpos[equipment]];
                text[7] = sfile[equipmentpos[equipment] + 1];
                text[8] = sfile[equipmentpos[equipment] + 2];
                text[9] = sfile[equipmentpos[equipment] + 3];
                text[10] = sfile[equipmentpos[equipment] + 4];
                text[11] = null;

                text[12] = sfile[tpos[test]];
                text[13] = sfile[tpos[test] + 1];
                text[14] = sfile[tpos[test] + 2];
                text[15] = sfile[tpos[test] + 3];
                text[16] = sfile[tpos[test] + 4];
                text[17] = sfile[tpos[test] + 5];
                text[18] = sfile[tpos[test] + 6];
                text[19] = sfile[tpos[test] + 7];
                text[20] = sfile[tpos[test] + 8];
                text[21] = sfile[tpos[test] + 9];
                text[22] = sfile[tpos[test] + 10];

                valid = true;
            }
             */
            pictureBox1.Refresh();

        }

        private void visualizarOsResultadosToolStripMenuItem_Click(object sender, EventArgs e)
        {
           // if (validtest)
           // {
                visualizadordicom.Aux_Forms.resultshomogeneidade results = new visualizadordicom.Aux_Forms.resultshomogeneidade(SNRroi, MPVroi, STDroi, totalsnr, totalMPV, totalSTD, nx, ny);

                results.ShowDialog();
           // }
        }

        private void adicionarÁreaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SARD.MainForms.MainForm main = (SARD.MainForms.MainForm)this.MdiParent;
            main.rect.Add(StartPoint);
            SARD.Aux_Forms.ROI roi = new SARD.Aux_Forms.ROI(main.rect, this.pictureBox1.Image);
            roi.Show();
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z1;
            this.unchekbox();
            this.toolStripMenuItem2.Checked = true;
            this.toolStripMenuItem9.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z2;
            this.unchekbox();
            this.toolStripMenuItem3.Checked = true;
            this.toolStripMenuItem10.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z3;
            this.unchekbox();
            this.toolStripMenuItem4.Checked = true;
            this.toolStripMenuItem11.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z4;
            this.unchekbox();
            this.toolStripMenuItem5.Checked = true;
            toolStripMenuItem12.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z5;
            this.unchekbox();
            this.toolStripMenuItem6.Checked = true;
            toolStripMenuItem13.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z6;
            this.unchekbox();
            this.toolStripMenuItem7.Checked = true;
            toolStripMenuItem14.Checked = true;
            this.SetLayout();
        }

        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
            this.z = (double)zoom.z7;
            this.unchekbox();
            this.toolStripMenuItem8.Checked = true;
            toolStripMenuItem15.Checked = true;
            this.SetLayout();
        }

        private void sToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("X: " + StartPoint.X.ToString() + "    Y: " + StartPoint.Y.ToString() +
               "    Comprimento: " + StartPoint.Width.ToString() + "    Altura: " + StartPoint.Height.ToString());
        }

        private void aoLongoDaVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (StartPoint.Height> 0)
            {
                visualizadordicom.Aux_Forms.brightprofile histogram = new visualizadordicom.Aux_Forms.brightprofile(dcmimage.returnbrightprofilevertical(StartPoint), StartPoint.Y);
                histogram.Show();
            }
        }

        private void aoLongoDaHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (StartPoint.Width> 0)
            {
                visualizadordicom.Aux_Forms.brightprofile histogram = new visualizadordicom.Aux_Forms.brightprofile(dcmimage.returnbrightprofilehorizontal(StartPoint), StartPoint.X);
                histogram.Show();
            }
        }

        private void visualizarGráficosDeConstânciaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (file != null)
            {
                visualizadordicom.Aux_Forms.testgraph graph = new visualizadordicom.Aux_Forms.testgraph(file);
                graph.Show();
            }
            else
            {
                SARD.Aux_Forms.local showoptions = new SARD.Aux_Forms.local();
                showoptions.ShowDialog();

                file = showoptions.getfile();


                visualizadordicom.Aux_Forms.testgraph graph = new visualizadordicom.Aux_Forms.testgraph(file);
                graph.Show();
            }

        }

        private void ajustarAoTamanhoDaTelaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.adjusttoscreen();
            this.unchekbox();
            ajustarAoTamanhoDaTelaToolStripMenuItem.Checked = true;
            ajustarAoTamanhoDaTelaToolStripMenuItem1.Checked = true;
            this.SetLayout();
        }

        private void ajustarAoTamanhoDaTelaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.adjusttoscreen();
            this.unchekbox();
            ajustarAoTamanhoDaTelaToolStripMenuItem.Checked = true;
            ajustarAoTamanhoDaTelaToolStripMenuItem1.Checked = true;
            this.SetLayout();
        }

        private void selecionarÁreaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (validtest)
            //    visualizarOsResultadosToolStripMenuItem.Enabled = true;
            //else
            //    visualizarOsResultadosToolStripMenuItem.Enabled = false;
        }

        private void selecionarÁreaToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            this.selection.setmode = selectionarea.mode.statical;
            this.selection.setoperation = selectionarea.operation.freesize;
        }

        private void homogeneidadeToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            if (roiarea == 0)
            {
                SARD.Aux_Forms.MTFform selectroiarea = new MTFform();
                selectroiarea.ShowDialog();
                roiarea = selectroiarea.returnsizex();
            }

            if (StartPoint.Width < roiarea || StartPoint.Height < roiarea)
            {
                MessageBox.Show("Área selecionada menor que a área de cálculo");
            }
            else if (roiarea > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                validtest = true;
                //This iteraction creates a superposition between the calculation areas.
                nx = (int)(1.5 * StartPoint.Width / roiarea + 1);
                ny = (int)(1.1 * StartPoint.Height / roiarea + 1);

                STDroi = new double[nx * ny];
                MPVroi = new double[nx * ny];
                SNRroi = new double[nx * ny];

                totalMPV = dcmimage.average(StartPoint);
                totalSTD = dcmimage.stddev(StartPoint);
                totalsnr = totalMPV / totalSTD;


                //It point was changed to improve accuracy, using int it is possible to loose some pixels in the path. To avoid it a float structure will be used.
                float shiftx = roiarea - (float)(nx * roiarea - StartPoint.Width) / (nx - 1);
                float shifty = roiarea - (float)(ny * roiarea - StartPoint.Height) / (ny - 1);


                for (int i = 0; i < nx; i++)
                    for (int j = 0; j < ny; j++)
                    {

                        STDroi[i + nx * j] = dcmimage.stddev(new Rectangle(StartPoint.X + (int)(shiftx * i), StartPoint.Y + (int)(shifty * j), roiarea, roiarea));
                        MPVroi[i + nx * j] = dcmimage.average(new Rectangle(StartPoint.X + (int)(shiftx * i), StartPoint.Y + (int)(shifty * j), roiarea, roiarea));
                        SNRroi[i + nx * j] = MPVroi[i + nx * j] / STDroi[i + nx * j];

                        //snrrel[i + nx * j] = 100 * Math.Round((SNRroi[i + nx * j] / totalsnr), 4);
                        //mpvrel[i + nx * j] = 100 * Math.Round((MPVroi[i + nx * j] / totalMPV), 4);

                    }

                //Find the maxmimum value in both vectors.
                /*
                int x = 0, y = 0;
                double m = mpvrel[0], s = snrrel[0];

                for (int i = 0; i < nx; i++)
                    for (int j = 0; j < ny; j++)
                    {
                        if (snrrel[i + nx * j] > s)
                        {
                            s = snrrel[i + nx * j];
                            x = i + nx * j;
                        }

                        if (mpvrel[i + nx * j] > m)
                        {
                            m = mpvrel[i + nx * j];
                            y = i + nx * j;
                        }

                    }

                if (m > s)
                {
                    s = m;
                    x = y;
                }

                if (s > 115 || s < 85)
                {
                    MessageBox.Show("Teste Reprovado");
                }
                else
                    MessageBox.Show("Teste aprovado");

                */

                this.Cursor = Cursors.Default;

                if (file != null)
                {
                    visualizadordicom.Aux_Forms.resultshomogeneidade results = new visualizadordicom.Aux_Forms.resultshomogeneidade(SNRroi, MPVroi, STDroi, totalsnr, totalMPV, totalSTD, nx, ny, file);

                    results.Show();
                }
                else
                {
                    visualizadordicom.Aux_Forms.resultshomogeneidade results = new visualizadordicom.Aux_Forms.resultshomogeneidade(SNRroi, MPVroi, STDroi, totalsnr, totalMPV, totalSTD, nx, ny);

                    results.Show();
                }
                /*
                 * The test result will be saved here, to do this you can use the file information that you already have.
                 * !!!
                     
                 */
            }

        }

        private void análiseEstatísticaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

                SARD.Statical calculateit;
                calculateit = new SARD.Statical(ref dcmimage, StartPoint);
                calculateit.Show();
                this.Cursor = Cursors.Default;

        }

        private void DicomImageBox_Resize(object sender, EventArgs e)
        {
            SetLayout();
        }

        private void panel1_Resize(object sender, EventArgs e)
        {
            SetLayout();
        }

        private void copiarImagemParaÁreaDeTrabalhoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetImage(pictureBox1.Image);
        }


    }     
    
}
